package com.cykj.user.service.impl;

import com.cykj.common.dto.ResponseDTO;
import com.cykj.user.util.CaptchaGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    private String smtpUsername;

    @Value("${captcha.length}")
    private int captchaLength;
    @Value("${captcha.expire-time}")
    private int expireTime;

    @Value("${captcha.cooldown-time}") // 默认冷却时间60秒
    private int cooldownTime;

    // 发送验证码邮件
    public ResponseDTO sendCaptchaEmail(String email) {
        // 1. 检查冷却时间
        String cooldownKey = "captcha:cooldown:" + email;
        if (redisTemplate.hasKey(cooldownKey)) {
            return ResponseDTO.error("不可重复发送验证码"); // 仍在冷却期内
        }

        // 2. 清理旧验证码（如果存在）
        String oldCaptchaKey = "captcha:" + email;
        redisTemplate.delete(oldCaptchaKey);
        // 生成验证码
        String captcha = CaptchaGenerator.generateCaptcha(captchaLength);
        // 存储到Redis，设置过期时间
        String key = "captcha:" + email;
        redisTemplate.opsForValue().set(key, captcha, expireTime, TimeUnit.MINUTES);
        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(smtpUsername); // 发送邮箱（与配置中一致）
        message.setTo(email);
        message.setSubject("验证码通知");
        message.setText("您的验证码为: " + captcha + "，有效期为" + expireTime + "分钟，请尽快使用。");
        mailSender.send(message);
        return ResponseDTO.success("验证码已发送");
    }

    // 验证邮箱验证码
    public boolean verifyCaptcha(String email, String captcha) {
        String key = "captcha:" + email;
        String storedCaptcha = redisTemplate.opsForValue().get(key);
        System.out.println(redisTemplate.opsForValue().get(key));
        if (storedCaptcha == null) {
            return false;
        }
        System.out.println(captcha);
        System.out.println(storedCaptcha.equalsIgnoreCase(captcha));
        return storedCaptcha.equalsIgnoreCase(captcha);
    }
}